﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Facebook.Schema;
using Omu.Awesome.Core;
using XPressify.Core;
using XPressify.Data;
using XPressify.Data.CompliedQueries;
using XPressify.Data.Helpers;
using XPressify.Helpers;
using XPressify.Models;

namespace XPressify.Controllers
{
    public class AlbumController : BaseController
    {
        private static int _newUploadFiles = 0;
        private static List<Media> newMedia = new List<Media>();
        //
        // GET: /Album/
        [Authorize]
        public ActionResult AlbumOwnerList(int? page)
        {
            var repo = Repository;
            var user = CurrentUser;
            var albums = AlbumCompiledQueries.GetAllAlbumsOfDesc(repo as Repository, user.Id);
            var albumPageable = albums.GetPageable(page ?? 1, 16, (g => g.Created));
            var model = new List<AlbumListModel>();
            foreach (var album in albumPageable.Page)
            {

                var numberOfMedias = AlbumCompiledQueries.GetMediasNumberOf(repo as Repository, album.Id);
                var isDeletable = true;
                if(album.IsProfile == true || album.IsWall == true)
                    isDeletable = false;
                
                var coverPicture = MediaCompiledQueries.GetCoverOf(repo as Repository, album.Id);
                if(album.IsProfile)
                    coverPicture = MediaCompiledQueries.GetProfileOf(repo as Repository, album.Id);
                var path = "";
                if (coverPicture != null && album.IsProfile == false) // if we have cover picture and its not profile
                    path = "/Media/" + user.Id + "/" + album.Id + "/" + coverPicture.Id + "." + coverPicture.FileType;
                if (coverPicture != null && album.IsProfile) //if we have cover picture and its profile album
                    path = "/Media/" + user.Id + "/" + album.Id + "/" + "ProfilePicture";
                else if (coverPicture == null && album.IsProfile == false) // if we dont have cover picture and its not profile album
                {
                    path = "/Media/Image/DefaultCover.jpg";
                }
                else if(coverPicture == null && album.IsProfile)// if we dont have cover picture and its profile album
                {
                    path = "/Media/Image/DefaultProfile.jpg";
                }
                
                
                var obj = new AlbumListModel
                              {
                                  SubjectId = user.Id,
                                  Id = album.Id,
                                  Name = album.Name,
                                  MediaCount = numberOfMedias,
                                  IsOwner = user.Id == AlbumCompiledQueries.GetAlbumSubjectId(repo as Repository, album.Id),
                                  IsDeletable = isDeletable,
                                  CoverPicturePath = path,
                                  SubjectName = user.FullName
                              };
                model.Add(obj);
            }
            var albumModelPageable = new Pageable<AlbumListModel> { Page = model, PageCount = albumPageable.PageCount, PageIndex = albumPageable.PageIndex };
            return View("AlbumList", albumModelPageable);
        }

        [Authorize]
        public ActionResult AlbumViewerList(Guid id, int? page) // album list from another user // with other user id parameter
        {
            var repo = Repository;
            var viewerUser = CurrentUser;
            var ownerUser = UserCompiledQueries.GetUser(repo as Repository, id);

            var isAjaxRequest = Request.IsAjaxRequest() ? true : false;
            var friends = true;
            var areFriendsOfFriends = true;
            if(ownerUser != null)
            {
                if(viewerUser.Id == ownerUser.Id)
                {
                    friends = true;
                    areFriendsOfFriends = true;
                }
                else
                {
                    friends = RelationshipCompiledQueries.AreFriends(repo as Repository, viewerUser.Id, ownerUser.Id); // check if current user is friend with selected user

                    var friendsOfFriends = Repository.GetFriendsOfFriendsOf(viewerUser.Id).Where(fr => fr.Id != ownerUser.Id);
                    areFriendsOfFriends = friendsOfFriends.Count() == 0 ? false : friendsOfFriends.Contains(viewerUser);
                }
                
            }
            else //if its page, event or group // then its alway true
            {
                friends = true;
                areFriendsOfFriends = true;
            }
            var albums = AlbumCompiledQueries.GetAlbumsOfDesc(repo as Repository, id, friends, areFriendsOfFriends);


//            var albumPageable = albums.GetPageable(page ?? 1, 16, (g => g.Created));


            var model = new List<AlbumListModel>();
            foreach (var album in albums)
            {

                var coverPicture = album.IsProfile ? MediaCompiledQueries.GetProfileOf(repo as Repository, album.Id) : MediaCompiledQueries.GetCoverOf(repo as Repository, album.Id);
                
                var path = "";
                if (coverPicture != null && album.IsProfile == false) // if we have cover picture and its not profile album
                    path = "/Media/" + ownerUser.Id + "/" + album.Id + "/" + coverPicture.Id + "." + coverPicture.FileType;
                else if (coverPicture != null && album.IsProfile) // if we have cover picture and its profile album
                    path = path = "/Media/" + ownerUser.Id + "/" + album.Id + "/" + "ProfilePicture";
                else if (coverPicture == null && album.IsProfile == false) // if we dont have cover picture and its not profile album
                {
                    path = "/Media/Image/DefaultCover.jpg";
                }
                else if (coverPicture == null && album.IsProfile)// if we dont have cover picture and its profile album
                {
                    path = "/Media/Image/DefaultProfile.jpg";
                }

                var numberOfMedias = AlbumCompiledQueries.GetMediasNumberOf(repo as Repository, album.Id);
                var obj = new AlbumListModel
                {
                    Id = album.Id,
                    Name = album.Name,
                    MediaCount = numberOfMedias,
                    CoverPicturePath = path,
                    SubjectId = id
                };
                model.Add(obj);
            }

            //get subject name and type
            var subjectName = "";
            short subjectType = -1;
            if(ownerUser != null)
            {
                subjectName = ownerUser.FullName;
                subjectType = ownerUser.Type;
            }
            else
            {
                var subjectEvent = EventCompiledQueries.GetEvent(repo as Repository, id);
                if(subjectEvent != null)
                {
                    subjectName = subjectEvent.FullName;
                    subjectType = subjectEvent.Type;
                }
                else
                {
                    var subjectGroup = GroupCompiledQueries.GetGroup(repo as Repository, id);
                    if (subjectGroup != null)
                    {
                        subjectName = subjectGroup.FullName;
                        subjectType = subjectGroup.Type;
                    }
                    else
                    {
                        var subjectPage = PageCompiledQueries.GetPage(repo as Repository, id);
                        if (subjectPage != null)
                        {
                            subjectName = subjectPage.FullName;
                            subjectType = subjectPage.Type;
                        }
                    }
                }
            }


            var newModel = new AlbumViewerListModel()
                               {
                                   Albums = model.ToArray(),
                                   IsAjaxRequest = isAjaxRequest,
                                   SubjectId = id,
                                   SubjectName = subjectName,
                                   SubjectType = subjectType
                               };
//            var albumModelPageable = new Pageable<AlbumListModel> { Page = model, PageCount = albumPageable.PageCount, PageIndex = albumPageable.PageIndex };
//            return View("AlbumList", albumModelPageable);
            return View("AlbumViewerList", newModel);
        }

        //
        // GET: /Album/Details/5
        [Authorize]
        public ActionResult AlbumDetails(Guid id)
        {
            var repo = Repository;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
            
            //postDummy is dummy post for liking and commenting on album
            var dummyPost = PostCompiledQueries.GetPostDummyAlbum(repo as Repository, album.Id);
            var allComments = Repository.GetAllComments(dummyPost);
            var currentUser = CurrentUser;
            var user = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
            var uploadedFiles = new List<UploadedFile>();
            var files = Directory.GetFiles(Server.MapPath("~/Media/" + user.Id + "/" + album.Id + "/"));
            var allFiles = MediaCompiledQueries.GetMediasOfDesc(repo as Repository, album.Id);

            foreach (var file in allFiles)
            {
                var fileFullName = file.IsProfile ? "ProfilePicture" : file.Name + "." + file.FileType;
                var fileName = file.IsProfile ? "ProfilePicture" : file.Name;
                var pathEnd = file.IsProfile ? "ProfilePicture" : file.Id + "." + file.FileType;
                var uploadedFile = new UploadedFile
                {
                    FullName = fileFullName,
                    Name = fileName,
                    Path = "/Media/" + user.Id + "/" + album.Id + "/" + pathEnd,
                    MediaType = GetMediaType(file.FileType),
                    Id = file.Id
                };
                uploadedFiles.Add(uploadedFile);
            }

            //get file size
            foreach (var file in files)
            {
                var fileInfo = new FileInfo(file);

                var fileId = Guid.Empty;

                if (fileInfo.Name != "ProfilePicture")
                {
                    fileId = new Guid(fileInfo.Name.Replace(fileInfo.Extension, ""));
                }
                else
                {
                    var profilePicture = MediaCompiledQueries.GetProfileOf(repo as Repository , album.Id);
                    fileId = profilePicture.Id;
                }
                var mediaFile = uploadedFiles.SingleOrDefault(x => x.Id == fileId);
                mediaFile.Size = fileInfo.Length;
            }

            //get owner of the album
            var owner = user.Type == SubjectType.User ? (User)user : null;
            var baseSubjectName = "";
            var baseSubjectId = Guid.Empty;
            if(owner == null)
            {
                baseSubjectName = user.FullName;
                if(album.BaseSubject.Type == SubjectType.Event)
                {
                    baseSubjectName = ((Event)user).Name;
                }
                baseSubjectId = user.Id;
            }


            //check if its owner of the album
            var isOwner = false;
            if (user.Type == SubjectType.User)
            {
                isOwner = user.Id == currentUser.Id;
            }
            else
            {
                //we try to find if there is any relationship which current user is administrator with BaseSubject(Group,Event,Page)
                isOwner = RelationshipCompiledQueries.IsAdministrator(repo as Repository, currentUser.Id,
                                                                      user.Id);
            }

            var model = new AlbumDetailsModel
                            {
                                Id = id,
                                Created = album.Created,
                                Description = album.Description,
                                IsOwner = isOwner,
                                Location = album.Location,
                                Name = album.Name,
                                AllFiles = uploadedFiles.ToArray(),
                                Owner = owner,
                                Viewer = currentUser,
                                AlbumPostDummyId = dummyPost.Id,
                                AllComments = allComments.ToArray(),
                                CurrentUserProfilePicturePath = Repository.GetProfilePicturePath(currentUser.Id),
                                BaseSubjectId = baseSubjectId,
                                BaseSubjectName = baseSubjectName,
                                Album = album
                            };

            return View(model);
        }

        //
        // GET: /Album/Create
        [Authorize]
        public ActionResult AlbumCreate()
        {
            var model = new AlbumCreateModel
                            {
                                ControllerName = "Album",
                                ActionName = "AlbumCreate"
                            };
            return View(model);
        } 

        //
        // POST: /Album/Create
        [Authorize]
        [HttpPost]
        public ActionResult AlbumCreate(AlbumCreateModel model)
        {
            if(ModelState.IsValid)
            {
                try
                {
                    var user = CurrentUser;
                    var album = new Album
                    {
                        BaseSubject = user,
                        Created = DateTime.Now,
                        Id = Guid.NewGuid(),
                        Description = model.Description,
                        Location = model.Location,
                        Name = model.Name,
                        Type = ObjectType.Album,
                        PrivacyType = model.PrivacyType,
                        MediaType = model.MediaType,
                        IsWall = false,
                        IsProfile = false
                    };

                    var path = Server.MapPath("~/Media/" + user.Id + "/" + album.Id + "/");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path); // create directory
                    }

                    var albumPostDummy = new Post()
                    {
                        BaseObject = album,
                        BaseSubject = user,
                        Content = "",
                        Id = Guid.NewGuid(),
                        Created = DateTime.Now,
                        Type = BaseMessageType.Post,
                        Title = "Post dummy - album",
                        Description = "Post dummy - album",
                        PostType = PostType.PostDummy,
                        CommentType = CommentType.PostWithGlobalComments
                    };

                    foreach (var postedFile in from string file in Request.Files select Request.Files[file])
                    {
                        if (!string.IsNullOrEmpty(postedFile.FileName))
                        {
                            var fileTypeArr = postedFile.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                            var fileType = fileTypeArr[fileTypeArr.Length - 1]; // type extension
                            var id = Guid.NewGuid();
                            var mediaType = GetMediaType(fileType);

                            var newFile = new Media
                            {
                                Id = id,
                                Album = album,
                                BaseSubject = user,
                                Created = DateTime.Now,
                                FileType = fileType,
                                Description = "",
                                PrivacyType = model.PrivacyType,
                                Type = ObjectType.Media,
                                MediaType = mediaType,
                                Name = ""
                            };
                            var filePath = path + newFile.Id + "." + fileType;
                            postedFile.SaveAs(filePath);
                            Repository.AddObject(newFile);
                        }


                    }
                    Repository.AddObject(album);
                    Repository.AddObject(albumPostDummy);
                    Repository.SaveChanges();

                    return Json(model);
//                    return RedirectToAction("AlbumDetails", "Album", new { id = album.Id });
                }
                catch
                {
                    return View(model);
                }
            }
            return View(model);
        }

        [Authorize]
        public ActionResult AlbumDummy(Guid id)
        {
            return RedirectToAction("AlbumFileEdit", "Album", new { id = id});
        }

        [Authorize]
        public ActionResult AlbumInfoEdit(Guid id)
        {
            var repo = Repository;
            var user = CurrentUser;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
            var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
            if (album == null || (user.Id != albumSubject.Id && albumSubject.Type == SubjectType.User)) // we check if current user is creator of album
            {
                return RedirectToAction("ProfileView", "Profile", new { id = user.Id });
            }
            var model = new AlbumEditInfoModel
                            {
                                Description = album.Description,
                                Id = album.Id,
                                Location = album.Location,
                                Name = album.Name,
                                PrivacyType = album.PrivacyType
                            };

            return View(model);
        }

        //
        // POST: /Album/Edit/5
        [Authorize]
        [HttpPost]
        public ActionResult AlbumInfoEdit(Guid id, AlbumEditInfoModel model)
        {
            if(ModelState.IsValid)
            {
                try
                {
                    var repo = Repository;
                    var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
                    album.Description = model.Description;
                    album.Location = model.Location;
                    album.Name = model.Name;
                    album.PrivacyType = model.PrivacyType;
                    Repository.SaveChanges();

                    return Json(model);
                }
                catch
                {
                    return View(model);
                }
            }
            return View(model);
        }

        //
        // GET: /Album/Edit/5
        [Authorize]
        public ActionResult AlbumPrivacyEdit(Guid id)
        {
            var repo = Repository;
            var currentUser = CurrentUser;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
            var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
            if (album == null || (currentUser.Id != albumSubject.Id && albumSubject.Type == SubjectType.User)) // we check if current user is creator of album
            {
                return RedirectToAction("ProfileView", "Profile", new { id = currentUser.Id });
            }
            var model = new AlbumEditPrivacyModel
            {
                Id = album.Id,
                PrivacyType = album.PrivacyType
            };

            return View(model);
        }

        //
        // POST: /Album/Edit/5
        [Authorize]
        [HttpPost]
        public ActionResult AlbumPrivacyEdit(Guid id, AlbumEditPrivacyModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var repo = Repository;
                    var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
                    bool changed = album.PrivacyType == model.PrivacyType;
                    album.PrivacyType = model.PrivacyType;

                    Repository.SaveChanges();
                    return Json(model);
                }
                catch
                {
                    return View(model);
                }
            }
            return View(model);
        }


        //
        // GET: /Album/Edit/5
        [Authorize]
        public ActionResult AlbumFileEdit(Guid id)
        {
            var repo = Repository;
            var currentUser = CurrentUser;
            var filesList = new List<Guid>();
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
            var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
            if (album == null || (currentUser.Id != albumSubject.Id && album.IsWall == false && albumSubject.Type == SubjectType.User)) // we check if current user is creator of album except wallAlbum
            {
                return RedirectToAction("ProfileView", "Profile", new { id = currentUser.Id });
            }

            //if current user is not owner of album and isWall but no new uploaded files then we redirect him to his profile
            if (album == null || (currentUser.Id != albumSubject.Id && album.IsWall == true && _newUploadFiles == 0 && albumSubject.Type == SubjectType.User))
            {
                return RedirectToAction("ProfileView", "Profile", new { id = currentUser.Id });
            }

            
            if(album.IsWall)
            {
                //if there are newly uploaded files then we create a post
                if (_newUploadFiles != 0 && newMedia.Count() != 0)
                {
                    
                    var newFile = newMedia.First();
                    var filePath = "/Media/" + albumSubject.Id + "/" + album.Id + "/" + newFile.Id + "." +
                                          newFile.FileType;
                    if (newFile.IsProfile)
                        filePath = "/Media/" + albumSubject.Id + "/" + album.Id + "/" + "ProfilePicture";
                    var newUploadedFile = new UploadedFileSelect
                    {
                        Id = newFile.Id,
                        Name = newFile.Name,
                        Path = filePath,
                        MediaType = GetMediaType(newFile.FileType),
                        FileExtension = newFile.FileType
                    };

                    //get profile picture
                    string profilePicturePath = Repository.GetProfilePicturePath(currentUser.Id);

                    //create a PostOnWall post
                    var newPost = new Post()
                    {
                        BaseObject = album,
                        BaseSubject = albumSubject, // owner of the post
                        Created = DateTime.Now,
                        Description = PostDescriptionType.PostOnWall +" file", 
                        PostType = PostType.Post,
                        Type = BaseMessageType.Post,
                        Id = Guid.NewGuid(),
                        Title = PostDescriptionType.PostOnWall + " file",
                        CommentType = CommentType.PostWithItsComments
                    };

                    //if user is posting on others friend wall
                    if (albumSubject.Id != currentUser.Id)
                    {
                        newPost.Creator = currentUser;
                    }

                    string postType = "";
                    if(newFile.MediaType == MediaType.Audio)
                    {
                        postType = "Audio";
                    }
                    else if(newFile.MediaType == MediaType.Document)
                    {
                        postType = "Document";
                    }
                    else if (newFile.MediaType == MediaType.Photo)
                    {
                        postType = "Photo";
                    }
                    else if (newFile.MediaType == MediaType.Video)
                    {
                        postType = "Video";
                    }
                    var picturePath = profilePicturePath;
                    var subjectId = currentUser.Id;
                    var subjectFullname = currentUser.FullName;
                    var isAdminPage = "false";

                    //check if its page and its admin if so then post will show that page posted something on wall
                    if (albumSubject.Type == SubjectType.Page)
                    {
                        var page = PageCompiledQueries.GetPage(repo as Repository, albumSubject.Id);
                        var isAdmin = RelationshipCompiledQueries.IsAdministrator(repo as Repository, currentUser.Id,
                                                                                  page.Id);
                        if (isAdmin)
                        {
                            subjectId = page.Id;
                            subjectFullname = page.FullName;
                            isAdminPage = "true";

                            //default cover picture path
                            var wallAlbum = AlbumCompiledQueries.GetAlbumBySubjectId(repo as Repository, page.Id);
                            picturePath = "/Media/" + albumSubject.Id + "/" + wallAlbum.Id + "/CoverPicture/CoverPicture";
                        }
                    }

                    var viewData = new
                    {
                        Id = subjectId,
                        ProfilePicturePath = picturePath,
                        Fullname = subjectFullname,
                        PostType = postType,
                        FilePath = filePath,
                        FileName = newFile.Name,
                        FileId = newFile.Id,
                        Description = newFile.Description,
                        Text = "",
                        Created = newPost.Created,
                        PostId = newPost.Id,
                        FileExtension = newUploadedFile.FileExtension,
                        IsAdminPage = isAdminPage
                    };

                    var viewDictionary = viewData.ToViewDataDictionary();
                    newPost.Content = ControlToString("~/Views/Post/PostOnWall.cshtml", viewDictionary);
                    Repository.AddObject(newPost);

                    // if current user is not owner of the album then we must create another post PostToFriend// only if baseSubject is user type
                    if (albumSubject.Id != currentUser.Id && albumSubject.Type == SubjectType.User)
                    {
                        //create a PostToFriend post
                        var newPost1 = new Post()
                        {
                            BaseObject = album,
                            BaseSubject = currentUser,
                            Created = newPost.Created,
                            Description = "PostToFriend file",
                            PostType = PostType.Post,
                            Type = BaseMessageType.Post,
                            Id = Guid.NewGuid(),
                            Title = "PostToFriend file",
                            CommentType = CommentType.PostWithoutComments
                        };
                        

                        var viewData1 = new
                        {
                            YourId = currentUser.Id,
                            ProfilePicturePath = profilePicturePath,
                            YourFullName = currentUser.FullName,
                            Filetype = "file",
                            FriendId = albumSubject.Id,
                            PostId = newPost1.Id,
                            FriendFullname = albumSubject.FullName,
                            Created = newPost1.Created
                        };

                        var viewDictionary1 = viewData1.ToViewDataDictionary();
                        newPost1.Content = ControlToString("~/Views/Post/PostToFriend.cshtml", viewDictionary1);
                        Repository.AddObject(newPost1);


                        // and we create one extra post that is special just for news feed// and it will look like user1 posted -> user2
                        // postToFriend post for news feed only
                        var newPost2 = new Post()
                        {
                            BaseObject = album,
                            BaseSubject = albumSubject, // owner of the post
                            Created = DateTime.Now,
                            Description = PostDescriptionType.PostOnWall + " file - newsfeed",
                            PostType = PostType.PostNewsFeed,
                            Type = BaseMessageType.Post,
                            Id = Guid.NewGuid(),
                            Title = PostDescriptionType.PostOnWall + " file - newsfeed",
                            CommentType = CommentType.PostWithItsComments,
                            Parent = newPost,
                            Creator = currentUser
                        };
                        var viewData2 = new
                        {
                            Id = currentUser.Id,
                            ProfilePicturePath = profilePicturePath,
                            Fullname = currentUser.FullName,
                            PostType = postType,
                            FilePath = filePath,
                            FileName = newFile.Name,
                            FileId = newFile.Id,
                            Description = newFile.Description,
                            Text = "",
                            Created = newPost.Created,
                            PostId = newPost.Id,
                            FileExtension = newUploadedFile.FileExtension,
                            FriendFullname = albumSubject.FullName,
                            FriendId = albumSubject.Id
                        };
                        var viewDictionary2 = viewData2.ToViewDataDictionary();
                        newPost2.Content = ControlToString("~/Views/Post/PostOnWallNewsFeed.cshtml", viewDictionary2);
                        Repository.AddObject(newPost2);

                        //UserPostedOnYourWall notification
                        var newNotification = new Notification()
                        {
                            Active = true,
                            BaseSubject = albumSubject,
                            Created = DateTime.Now,
                            Id = Guid.NewGuid(),
                            Type = BaseMessageType.Notification
                        };
                        var viewData3 = new
                        {
                            UserId = currentUser.Id,
                            UserFullname = currentUser.FullName,
                            YourId = albumSubject.Id,
                            PostId = newPost.Id
                        };

                        var viewDictionary3 = viewData3.ToViewDataDictionary();
                        newNotification.Content = ControlToString("~/Views/Notification/UserPostedOnYourWall.cshtml", viewDictionary3);
                        Repository.AddObject(newNotification);
                    }

                    //if group then we create PostOnGroupEventPage notification for every member
                    if (albumSubject.Type == SubjectType.Group)
                    {
                        var group = GroupCompiledQueries.GetGroup(repo as Repository, albumSubject.Id);
                        var members = Repository.GetMembersOf(group.Id).Where(mem => mem.Id != currentUser.Id).ToList();
                        var admin = Repository.GetAdminOf(group.Id);
                        members.Add(admin);
                        foreach (var member in members)
                        {
                            var newNotification = new Notification()
                            {
                                Active = true,
                                BaseSubject = member,
                                Created = DateTime.Now,
                                Id = Guid.NewGuid(),
                                Type = BaseMessageType.Notification
                            };
                            var viewData3 = new
                            {
                                UserPostedId = currentUser.Id,
                                UserPostedFullname = currentUser.FullName,
                                BaseSubjectType = "group",
                                SubjectId = group.Id,
                                SubjectFullname = group.FullName,
                                PostId = newPost.Id
                            };

                            var viewDictionary3 = viewData3.ToViewDataDictionary();
                            newNotification.Content = ControlToString("~/Views/Notification/PostOnGroupEventPage.cshtml", viewDictionary3);
                            Repository.AddObject(newNotification);
                        }

                    }

                    Repository.SaveChanges();

                    newMedia.Clear(); // clears all data
                    _newUploadFiles = 0; // reset to zero


                    if (Request.IsAjaxRequest())
                    {
                        var newModel = new CommentPostModel()
                        {
                            Post = newPost,
                            ViewerProfilePicturePath = profilePicturePath
                        };
                        return PartialView("Post", newModel);
                    }

                    var newModel1 = new AlbumEditPrivacyModel();
                    return RedirectToAction("AlbumDetails", "Album", new { id = album.Id });
                }
            }


            var files = Directory.GetFiles(Server.MapPath("~/Media/" + albumSubject.Id + "/" + id + "/"));
            var uploadedFiles = new List<UploadedFileSelect>();
            var allFiles = MediaCompiledQueries.GetMediasOfDesc(repo as Repository, album.Id);

            foreach (var file in allFiles)
            {
                var fileFullName = file.IsProfile ? "ProfilePicture" : file.Name + "." + file.FileType;
                var fileName = file.IsProfile ? "ProfilePicture" : file.Name;
                var pathEnd = file.IsProfile ? "ProfilePicture" : file.Id + "." + file.FileType;
                

                var uploadedFile = new UploadedFileSelect
                {
                    Id = file.Id,
                    Name = fileName,
                    Path = "/Media/" + albumSubject.Id + "/" + id + "/" + pathEnd,
                    MediaType = GetMediaType(file.FileType),
                    Selected = false,
                    Description = file.Description,
                    FullName = fileFullName
                };

                uploadedFiles.Add(uploadedFile);
            }

            //get file size
            foreach (var file in files)
            {
                var fileInfo = new FileInfo(file);

                var fileId = Guid.Empty;

                if (fileInfo.Name != "ProfilePicture")
                {
                    fileId = new Guid(fileInfo.Name.Replace(fileInfo.Extension, ""));
                }
                else
                {
                    var profilePicture = MediaCompiledQueries.GetProfileOf(repo as Repository, album.Id);
                    fileId = profilePicture.Id;
                }
                var mediaFile = uploadedFiles.SingleOrDefault(x => x.Id == fileId);
                mediaFile.Size = fileInfo.Length;
            }

            var coverPicture = MediaCompiledQueries.GetCoverOf(repo as Repository, id);
            bool hasCover = false;
            var coverPictureId = Guid.Empty;
            if (coverPicture != null) // if it cant find any covery picture that means that album doesnt have cover
            {
                hasCover = true;
                coverPictureId = coverPicture.Id;
            }

            var ownerIsUser = albumSubject.Type == SubjectType.User ? true : false;
   
            var model = new AlbumEditPhotoModel
            {
                UploadedFiles = uploadedFiles.ToArray(),
                Id = album.Id,
                HasCover = hasCover,
                CoverPicture = coverPictureId,
                isProfileAlbum = album.IsProfile,
                isWallAlbum = album.IsWall,
                AlbumName = album.Name,
                OwnerIsUser = ownerIsUser,
                SelectedProfilePicture = Guid.Empty
            };

            
            return View(model);
        }

        //
        // POST: /Album/Edit/5
        [Authorize]
        [HttpPost]
        public ActionResult AlbumFileEdit(Guid id, AlbumEditPhotoModel model)
        {
            if(ModelState.IsValid)
            {
                try
                {
                    var repo = Repository;
                    var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
                    var files = MediaCompiledQueries.GetMediasOfDesc(repo as Repository, id);
                    var user = CurrentUser;
                    var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
                    if(files == null || files.Count() == 0)
                        return RedirectToAction("AlbumOwnerList");
                    for(var i = 0; i < model.UploadedFiles.Length; i++)
                    {
                        var file = MediaCompiledQueries.GetMedia(repo as Repository, model.UploadedFiles[i].Id);
                        if (model.UploadedFiles[i].Selected) // if the file is selected to be deleted
                        {
                            var filePath = "";
//                            var mediaSubject = MediaCompiledQueries.GetMediaSubject(repo as Repository, file.Id);
                            filePath = file.IsProfile == false ? GetPath(file) : Server.MapPath("~/Media/" + albumSubject.Id + "/" + album.Id + "/" + "ProfilePicture");
                            var fileInfo = new FileInfo(filePath);
                            if(file.IsProfile) // if selected picture is profile then we must take another one as a profile
                            {
                                fileInfo.Delete();

                                Repository.DeleteObject(file);
                                Repository.SaveChanges();
                                var nextProfile = MediaCompiledQueries.GetMediasOfDesc(repo as Repository, id);
                                if(nextProfile != null && nextProfile.Count() != 0) // if exist some pictures in profile album we take randomly the next one as profile
                                {
                                    var newProfile = (Media)nextProfile.ElementAt(0);
                                    newProfile.IsProfile = true;
//                                    var newProfileSubject = MediaCompiledQueries.GetMediaSubject(repo as Repository, newProfile.Id);
                                    var oldPath =
                                        Server.MapPath("~/Media/" + albumSubject.Id + "/" +
                                                       album.Id + "/" + newProfile.Id + "." +
                                                       newProfile.FileType);
                                    var newPath =
                                        Server.MapPath("~/Media/" + albumSubject.Id + "/" +
                                                       album.Id + "/" + "ProfilePicture");
                                    var profileInfo = new FileInfo(oldPath);
                                    profileInfo.CopyTo(newPath);
                                    profileInfo.Delete();
                                }
                                else // if there is no other picture in profile album then we create a default profile picture and set it as profile
                                {
                                    var defaultProfilePicture = Server.MapPath("/Media/Image/DefaultProfile.jpg");
                                    var newProfilePicturePath = Server.MapPath("~/Media/" + user.Id + "/" + album.Id + "/" + "ProfilePicture");
                                    fileInfo = new FileInfo(defaultProfilePicture);
                                    fileInfo.CopyTo(newProfilePicturePath);
                                    var newProfile = new Media() // create a clone media to make it as a profile
                                    {
                                        Id = Guid.NewGuid(),
                                        Album = album,
                                        BaseSubject = user,
                                        Created = DateTime.Now,
                                        Description = "",
                                        FileType = "jpg",
                                        IsProfile = true,
                                        IsCover = false, // cannot be cover of profile album
                                        MediaType = MediaType.Photo,
                                        Name = "Picture",
                                        PrivacyType = album.PrivacyType, // set a privacy of album
                                        Type = ObjectType.Media
                                    };
                                    newProfile.Name = newProfile.Id.ToString();

                                    var mediaPostDummy = new Post()
                                    {
                                        BaseObject = newProfile,
                                        BaseSubject = user,
                                        Content = "",
                                        Id = Guid.NewGuid(),
                                        Created = DateTime.Now,
                                        Type = BaseMessageType.Post,
                                        Title = "Post dummy - media",
                                        Description = "Post dummy - media",
                                        PostType = PostType.PostDummy,
                                        CommentType = CommentType.PostWithItsComments
                                    };

                                    Repository.AddObject(newProfile);
                                    Repository.AddObject(mediaPostDummy);
                                    Repository.SaveChanges();
                                }
                            }
                            else
                            {
                                //if its cover to be deleted and its page then we copy default one to default cover picture path
                                if (file.IsCover && albumSubject.Type == SubjectType.Page)
                                {
//                                    var fileSubject = MediaCompiledQueries.GetMediaSubject(repo as Repository, file.Id);   
                                    var oldPath =
                                        Server.MapPath("~/Media/Image/DefaultCover.jpg");
                                    //if page copy to the default cover picture path
                                    var defaultCoverPath = Server.MapPath("~/Media/" + albumSubject.Id + "/" +
                                                           album.Id + "/" + "CoverPicture/CoverPicture");
                                    var oldInfo = new FileInfo(oldPath);
                                    oldInfo.CopyTo(defaultCoverPath,true);
                                }
                                fileInfo.Delete();
                                Repository.DeleteObject(file);
                            }
                            
                        }
                        else // we change name, decription, IsCover and IsProfile
                        {
                            file.Description = model.UploadedFiles[i].Description;
//                            var fileSubject = MediaCompiledQueries.GetMediaSubject(repo as Repository, file.Id);  
                            file.Name = file.IsProfile ? file.Name : model.UploadedFiles[i].Name;
                            if(file.Id == model.SelectedCoverPicture) // if file is selected as cover picture
                            {
                                if(model.HasCover) // if album has previous cover picture then we must set its attribute IsCover to false
                                {
                                    var previousCover = MediaCompiledQueries.GetCoverOf(repo as Repository, album.Id);
                                    if(previousCover != null)
                                        previousCover.IsCover = false;
                                }
                                //if page copy to the default cover picture path also
                                if (albumSubject.Type == SubjectType.Page)
                                {
                                    var toBeCoverPath = Server.MapPath("~/Media/" + albumSubject.Id + "/" +
                                                           album.Id + "/" + file.Id + "." + file.FileType);
                                    var toBeInfo = new FileInfo(toBeCoverPath);
                                    var defaultCoverPath =
                                        Server.MapPath("~/Media/" + albumSubject.Id + "/" +
                                                       album.Id + "/" + "CoverPicture/CoverPicture");
                                    toBeInfo.CopyTo(defaultCoverPath, true);
                                }
                                file.IsCover = true;
                            }
                            if(file.Id == model.SelectedProfilePicture) // if file is selelcted as profile picture
                            {
                                var profileAlbum = AlbumCompiledQueries.GetProfileAlbum(repo as Repository, user.Id);
                                var oldProfilePicture = MediaCompiledQueries.GetProfileOf(repo as Repository,
                                                                                          profileAlbum.Id);
                                
                                if(album.IsProfile) // then we dont create new picture
                                {
                                    //if exist profile picture already
                                    if (oldProfilePicture != null)
                                    {
                                        oldProfilePicture.IsProfile = false;
                                        //get old profile picture path and change it
                                        var oldProfilePath = Server.MapPath("~/Media/" + user.Id + "/" + profileAlbum.Id + "/" + "ProfilePicture"); // old path of old profile picture
                                        oldProfilePicture.Name = oldProfilePicture.Id.ToString();
                                        var newProfilePath = Server.MapPath("~/Media/" + user.Id + "/" + profileAlbum.Id + "/" + oldProfilePicture.Id + "." + oldProfilePicture.FileType); // new path for previous profile pic
                                        var fileInfo = new FileInfo(oldProfilePath);
                                        fileInfo.CopyTo(newProfilePath); // copy to new path
                                        fileInfo.Delete(); // and delete the old profile picture
                                    }
                                    file.IsProfile = true;
                                    var oldPath = Server.MapPath("~/Media/" + user.Id + "/" + profileAlbum.Id + "/" + file.Id + "." + file.FileType); // old path from the new profile picture we delete
                                    var newPath = Server.MapPath("~/Media/" + user.Id + "/" + profileAlbum.Id + "/" + "ProfilePicture");
                                    var newFileInfo = new FileInfo(oldPath);
                                    newFileInfo.CopyTo(newPath,true); // copy to the new path which is ending with ProfilePicture // standard for everyones profiles
                                    newFileInfo.Delete(); // and delete the old path for new profile pic
                                }
                                else // we create a new profile picture
                                {
                                    var newProfile = new Media() // create a clone media to make it as a profile
                                    {
                                        Id = Guid.NewGuid(),
                                        Album = profileAlbum,
                                        BaseSubject = user,
                                        Created = file.Created,
                                        Description = file.Description,
                                        FileType = file.FileType,
                                        IsProfile = true,
                                        IsCover = false, // cannot be cover of profile album
                                        MediaType = file.MediaType,
                                        Name = file.Name,
                                        PrivacyType = profileAlbum.PrivacyType, // set a privacy of album
                                        Type = file.Type
                                    };
                                    newProfile.Name = newProfile.Id.ToString();

                                    var mediaPostDummy = new Post()
                                    {
                                        BaseObject = newProfile,
                                        BaseSubject = user,
                                        Content = "",
                                        Id = Guid.NewGuid(),
                                        Created = DateTime.Now,
                                        Type = BaseMessageType.Post,
                                        Title = "Post dummy - media",
                                        Description = "Post dummy - media",
                                        PostType = PostType.PostDummy,
                                        CommentType = CommentType.PostWithItsComments
                                    };

                                    //if old profile picture exists
                                    if(oldProfilePicture != null)
                                    {
                                        oldProfilePicture.IsProfile = false;
                                        //get old profile picture path and change it
                                        var oldPath = Server.MapPath("~/Media/" + user.Id + "/" + profileAlbum.Id + "/" + "ProfilePicture"); // old path of old profile picture
                                        oldProfilePicture.Name = oldProfilePicture.Id.ToString();
                                        var newPath = Server.MapPath("~/Media/" + user.Id + "/" + profileAlbum.Id + "/" + oldProfilePicture.Id + "." + oldProfilePicture.FileType); // new path for previous profile pic
                                        var oldFileInfo = new FileInfo(oldPath);
                                        oldFileInfo.CopyTo(newPath); // copy the old profile picture to the new path
                                        oldFileInfo.Delete(); // and delete the old profile picture from old path
                                    }
                                    Repository.AddObject(newProfile); // add newProfile picture to repository
                                    Repository.AddObject(mediaPostDummy);

                                    //copy a ex profile file to new made copy file 
                                    var selectedProfilePath = Server.MapPath("~/Media/" + user.Id + "/" + album.Id + "/" + file.Id + "." + file.FileType); // old path 
                                    var newlyCreatedPicture = Server.MapPath("~/Media/" + user.Id + "/" + profileAlbum.Id + "/" + newProfile.Id + "." + newProfile.FileType);
                                    var oldProfileInfo = new FileInfo(selectedProfilePath);
                                    oldProfileInfo.CopyTo(newlyCreatedPicture); // copy to the new path which is ending with ProfilePicture // standard for everyones profiles

                                    //copy a new made copy file to ProfilePicture file
                                    var standardProfilePath = Server.MapPath("~/Media/" + user.Id + "/" + profileAlbum.Id + "/" + "ProfilePicture");

                                    var newlyCreatedPictureInfo = new FileInfo(newlyCreatedPicture);
                                    newlyCreatedPictureInfo.CopyTo(standardProfilePath); // copy it to new file
                                    newlyCreatedPictureInfo.Delete();
                                }

                            }
                        }
                    }
                    Repository.SaveChanges();

                    //if there are newly uploaded files then we create a post
                    if(_newUploadFiles != 0)
                    {
                        var allFiles = newMedia;//album.Medias.OrderByDescending(al => al.Created);
                        var index = 1;
                        var newUploadedFiles = new List<UploadedFileSelect>();
                        foreach (var file in allFiles) // try to find newly uploaded files and add them to the list
                        {
                            if (index > _newUploadFiles || index > 3) // must not extend 3 or _newUploadedFiles number, cause it will show maximum 3 new uploaded files
                                break;
                            var picturePath = "/Media/" + user.Id + "/" + album.Id + "/" + file.Id + "." +
                                              file.FileType;
                            if(file.IsProfile)
                                picturePath = "/Media/" + user.Id + "/" + album.Id + "/" + "ProfilePicture";
                            var newUploadedFile = new UploadedFileSelect
                                                      {
                                                          Id = file.Id,
                                                          Name = file.Name,
                                                          Path = picturePath,
                                                          MediaType = GetMediaType(file.FileType),
                                                          FileExtension = file.FileType
                                                      };
                            newUploadedFiles.Add(newUploadedFile);
                            index++;
                        }

                        //get profile picture
                        string profilePicturePath = Repository.GetProfilePicturePath(user.Id);

                        //create a UploadFile post
                        var newPost = new Post()
                        {
                            BaseObject = album,
                            BaseSubject = user,
                            Created = DateTime.Now,
                            Description = "Upload files",
                            PostType = PostType.Post,
                            Type = BaseMessageType.Post,
                            Id = Guid.NewGuid(),
                            Title = "Upload files",
                            CommentType = CommentType.PostWithGlobalComments
                        };
                        var viewData = new
                        {
                            YourProfilePicturePath = profilePicturePath,
                            YourFullName = user.FullName,
                            YourId = user.Id,
                            AlbumDescription = album.Description,
                            Files = newUploadedFiles,
                            AlbumName = album.Name,
                            AlbumId = album.Id,
                            Created = newPost.Created,
                            PostId = newPost.Id
                        };

                        var viewDictionary = viewData.ToViewDataDictionary();
                        newPost.Content = ControlToString("~/Views/Post/UploadFile.cshtml", viewDictionary);
                        Repository.AddObject(newPost);
                        Repository.SaveChanges();

                        newMedia.Clear(); // clear all 
                        _newUploadFiles = 0; // reset to zero

                    }
                    if (album.BaseSubject.Type == SubjectType.Event)
                    {
                        return RedirectToAction("EventDetails", "Event", new { id = albumSubject.Id });
                    }
                    if (album.BaseSubject.Type == SubjectType.Group)
                    {
                        return RedirectToAction("GroupDetails", "Group", new { id = albumSubject.Id });
                    }
                    if (album.BaseSubject.Type == SubjectType.Page)
                    {
                        return RedirectToAction("PageDetails", "Page", new { id = albumSubject.Id });
                    }
                    return RedirectToAction("AlbumDetails", "Album", new {id = album.Id});
                }
                catch
                {
                    return View(model);
                }
            }
            return View(model); 
            
        }


        //
        // GET: /Album/Delete/5
        [Authorize]
        public ActionResult AlbumDelete(Guid id)
        {
            var repo = Repository;
            var user = CurrentUser;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id); 
            var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, id);
            if (album == null || user.Id != albumSubject.Id) // we check if current user is creator of album
            {
                return RedirectToAction("ProfileView", "Profile", new { id = user.Id });
            }
            var pictures = MediaCompiledQueries.GetMediasOfDesc(repo as Repository, album.Id);
            var path = Server.MapPath("~/Media/" + user.Id + "/" + album.Id + "/");
            foreach (var picture in pictures)
            {
                Repository.DeleteObject(picture);
            }
            Repository.DeleteObject(album);
            Repository.SaveChanges();
            Directory.Delete(path, true);
            return RedirectToAction("AlbumOwnerList", "Album", new { id = user.Id });;
        }

        [Authorize]
        public ActionResult ImageGallery(Guid id)
        {
            var repo = Repository;
            var image = MediaCompiledQueries.GetMedia(repo as Repository, id); 
            var album = AlbumCompiledQueries.GetAlbumByMediaId(repo as Repository, image.Id);
            var allPictures = MediaCompiledQueries.GetPhotoMediasOfDesc(repo as Repository, album.Id);
            var imageSubject = MediaCompiledQueries.GetMediaSubject(repo as Repository, image.Id);
            var listImages = new List<ImageModel>();
            var index = 0;
            var choosedImageIndex = 0;
            foreach (var picture in allPictures)
            {
                var picturePath = "/Media/" + imageSubject.Id + "/" + album.Id + "/" + picture.Id + "." +
                                  picture.FileType;
                if(picture.IsProfile)
                {
                    picturePath = "/Media/" + imageSubject.Id + "/" + album.Id + "/ProfilePicture";
                }
                if(picture.Id == image.Id)
                {
                    choosedImageIndex = index;
                }
                var newImage = new ImageModel()
                                   {
                                       Description = picture.Description,
                                       Id = picture.Id,
                                       PicturePath = picturePath
                                   };
                listImages.Add(newImage);
                index++;
            }

            //get subject type// (user, event, group, page)
            var subjectType = imageSubject.Type;
            
            var model = new ImageGalleryModel()
                            {
                                Images = listImages.ToArray(),
                                IndexImage = choosedImageIndex,
                                AlbumId = album.Id,
                                SubjectId = imageSubject.Id,
                                SubjectType = subjectType,
                                SubjectName = imageSubject.FullName,
                                Album = album
                            };

            return View(model);
        }

        [Authorize]
        public ActionResult CommentsList(string path)
        {
            var currentUser = CurrentUser;
            var arr = path.Split('/');
            var pictureIdString = arr.Last();
            Media picture;
            var repo = Repository;
            //if its profile picture then physical name of the file is ProfilePicture and we must look for the album and then its profile media to find picture
            if(pictureIdString == "ProfilePicture")
            {
                //second from behind is album id // path: ~Media/UserId/AlbumId/MediaId.extension
                var albumIdString = arr.ElementAt(arr.Length - 2);
                var albumId = new Guid(albumIdString);
                var album = AlbumCompiledQueries.GetAlbum(repo as Repository, albumId);
                picture = MediaCompiledQueries.GetProfileOf(repo as Repository, albumId);

            }
            else
            {
                pictureIdString = arr.Last().Split('.')[0]; // remove extension of file // .jpg , .jpeg ect.
                var pictureId = new Guid(pictureIdString);
                picture = MediaCompiledQueries.GetMedia(repo as Repository, pictureId);
            }

            var postDummy = PostCompiledQueries.GetPostDummyMedia(repo as Repository, picture.Id);
            var pictureSubject = MediaCompiledQueries.GetMediaSubject(repo as Repository, picture.Id);
            var allComments = Repository.GetAllComments(postDummy);
            var model = new CommentsListModel()
                            {
                                Comments = allComments.ToArray(),
                                PostDummy = postDummy,
                                CurrentUserId = currentUser.Id,
                                IsOwner = pictureSubject.Id == currentUser.Id,
                                ProfilePicturePath = Repository.GetProfilePicturePath(currentUser.Id),
                                Created = picture.Created
                            };
            return PartialView(model);
        }


        #region Upload File

        [Authorize]
        public ActionResult AlbumUploadFileSimple(Guid id)
        {
            var repo = Repository;
            var user = CurrentUser;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
            var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
            if (album == null || (user.Id != albumSubject.Id && album.IsWall == false)) // we check if current user is creator of album except wallAlbum cause somebody else can upload on wallAlbum
            {
                return RedirectToAction("ProfileView", "Profile", new { id = user.Id });
            }
            var singleUpload = false;
            if (album.IsWall)
                singleUpload = true;
            var model = new AlbumUploadFileModel
            {
                Id = id,
                ActionName = "AlbumUploadFileSimple",
                ControllerName = "Album",
                SingleUpload = singleUpload,
                SingleUploadDescription = ""
            };
            return View(model);
        }

        [Authorize]
        [HttpPost]
        public ActionResult AlbumUploadFileSimple(Guid id, AlbumUploadFileModel model)
        {
            var repo = Repository;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
//                Repository.AsQueryable<Album>().SingleOrDefault(al => al.Id == id);
            var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
            var path = Server.MapPath("~/Media/" + albumSubject.Id + "/" + album.Id + "/");
            string fileExtension = GetExtensions(id);
            foreach (var postedFile in from string file in Request.Files select Request.Files[file])
            {
                if (!string.IsNullOrEmpty(postedFile.FileName))
                {
                    var fileTypeArr = postedFile.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                    var fileType = fileTypeArr[fileTypeArr.Length - 1]; // type extension
                    var fileId = Guid.NewGuid();
                    var mediaType = GetMediaType(fileType);
                    var fileName = postedFile.FileName.Replace("." + fileType, "");
                    if(!fileExtension.Contains(fileType.ToLower())) // we create file extension filter and if not matched we dont save the file
                        continue;
                    var desc = "";
                    if (model.SingleUploadDescription != null)
                        desc = model.SingleUploadDescription;
                    var newFile = new Media
                    {
                        Id = fileId,
                        Album = album,
                        BaseSubject = albumSubject,
                        Created = DateTime.Now,
                        FileType = fileType,
                        Description = desc,
                        PrivacyType = album.PrivacyType,
                        Type = ObjectType.Media,
                        MediaType = mediaType,
                        Name = fileName
                    };
                    newMedia.Add(newFile);

                    var mediaPostDummy = new Post()
                    {
                        BaseObject = newFile,
                        BaseSubject = albumSubject,
                        Content = "",
                        Id = Guid.NewGuid(),
                        Created = DateTime.Now,
                        Type = BaseMessageType.Post,
                        Title = "Post dummy - media",
                        Description = "Post dummy - media",
                        PostType = PostType.PostDummy,
                        CommentType = CommentType.PostWithItsComments
                    };

                    var filePath = path + newFile.Id + "." + fileType;
                    postedFile.SaveAs(filePath); // save file
                    Repository.AddObject(newFile); // save object connected to file
                    Repository.AddObject(mediaPostDummy);
                    _newUploadFiles++;
                }
            }
            Repository.SaveChanges();
            return RedirectToAction("AlbumFileEdit", "Album", new {id = album.Id});
        }



        //this is upload file with ajax
        [Authorize]
        public ActionResult AlbumUploadFile(Guid id)
        {
            var repo = Repository;
            var user = CurrentUser;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
            var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
            if (album == null || (user.Id != albumSubject.Id && album.IsWall == false)) // we check if current user is creator of album except wallAlbum cause somebody else can upload on wallAlbum
            {
                return RedirectToAction("ProfileView", "Profile", new { id = user.Id });
            }
            string fileExtension = GetExtensionsForUploadFile(id);
            var singleUpload = false;
            if (album.IsWall)
                singleUpload = true;
            var model = new AlbumUploadFileModel
            {
                Id = id,
                ActionName = "AlbumUploadFile",
                ControllerName = "Album",
                UserId = user.Id,
                FileExtension = fileExtension,
                SingleUpload = singleUpload,
                SingleUploadDescription = "",
                OwnerId = albumSubject.Id
            };
            return View(model);
        }

        //this is upload file with ajax
        [Authorize]
        public ActionResult AlbumUploadFileNormal(Guid id)
        {
            var repo = Repository;
            var user = CurrentUser;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
            var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
            if (album == null || (user.Id != albumSubject.Id && album.IsWall == false)) // we check if current user is creator of album except wallAlbum cause somebody else can upload on wallAlbum
            {
                return RedirectToAction("ProfileView", "Profile", new { id = user.Id });
            }
            string fileExtension = GetExtensionsForUploadFile(id);
            var singleUpload = false;
            if (album.IsWall)
                singleUpload = true;
            var model = new AlbumUploadFileModel
            {
                Id = id,
                ActionName = "AlbumUploadFile",
                ControllerName = "Album",
                UserId = user.Id,
                FileExtension = fileExtension,
                SingleUpload = singleUpload,
                SingleUploadDescription = "",
                OwnerId = albumSubject.Id
            };
            return View("AlbumUploadFileNormal", model);
        }

        [HttpPost]
        public ActionResult AlbumUploadFile(Guid albumId, Guid userId, string token, HttpPostedFileBase fileData, string description)
        {

            var ticket = FormsAuthentication.Decrypt(token);
            if (ticket != null)
            {
                var identity = new FormsIdentity(ticket);
                if (identity.IsAuthenticated)
                {
                    try
                    {
                        var repo = Repository;
                        var album = AlbumCompiledQueries.GetAlbum(repo as Repository, albumId);
                        var user = UserCompiledQueries.GetUser(repo as Repository, userId);
                        var albumSubject = AlbumCompiledQueries.GetAlbumSubject(repo as Repository, album.Id);
                        var path = Server.MapPath("~/Media/" + albumSubject.Id + "/" + album.Id + "/");
                        if (!string.IsNullOrEmpty(fileData.FileName))
                        {
                            var fileTypeArr = fileData.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                            var fileType = fileTypeArr[fileTypeArr.Length - 1]; // type extension
                            var fileId = Guid.NewGuid();
                            var mediaType = GetMediaType(fileType);
                            var fileName = fileData.FileName.Replace("." + fileType, "");
                            var desc = "";
                            if (description != null)
                                desc = description;
                            var newFile = new Media
                            {
                                Id = fileId,
                                Album = album,
                                BaseSubject = albumSubject,
                                Created = DateTime.Now,
                                FileType = fileType,
                                Description = desc,
                                PrivacyType = album.PrivacyType,
                                Type = ObjectType.Media,
                                MediaType = mediaType,
                                IsProfile = false,
                                IsCover = false,
                                Name = fileName
                            };

                            newMedia.Add(newFile); // for making PostOnWall post

                            var mediaPostDummy = new Post()
                            {
                                BaseObject = newFile,
                                BaseSubject = albumSubject,
                                Content = "",
                                Id = Guid.NewGuid(),
                                Created = DateTime.Now,
                                Type = BaseMessageType.Post,
                                Title = "Post dummy - media",
                                Description = "Post dummy - media",
                                PostType = PostType.PostDummy,
                                CommentType = CommentType.PostWithItsComments
                            };

                            var filePath = path + newFile.Id + "." + fileType;
                            fileData.SaveAs(filePath);
                            Repository.AddObject(newFile);
                            Repository.AddObject(mediaPostDummy);
                            Repository.SaveChanges();
                            _newUploadFiles++;
                        }
                        //Save file and other code removed
                        return Content("File uploaded successfully!");
                    }
                    catch (Exception ex)
                    {
                        return Content("Error uploading file: " + ex.Message);
                    }
                }
            }
            throw new InvalidOperationException("The user is not authenticated.");
        }

#endregion

        #region Helper Methods

        private short GetMediaType(string fileType)
        {
            
            if (SupportedMediaTypes.VideoTypes.Contains(fileType.ToLower()))
            {
                return MediaType.Video;
            }

            if (SupportedMediaTypes.PhotoTypes.Contains(fileType.ToLower()))
            {
                return MediaType.Photo;
            }

            if (SupportedMediaTypes.DocumentTypes.Contains(fileType.ToLower()))
            {
                return MediaType.Document;
            }

            if (SupportedMediaTypes.AudioTypes.Contains(fileType.ToLower()))
            {
                return MediaType.Audio;
            }

            return -1;
        }

        private string GetExtensions(Guid id)
        {
            var repo = Repository;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
            if (album.MediaType == AlbumMediaType.Audio)
            {
                return SupportedMediaTypes.AudioTypes;
            }

            if (album.MediaType == AlbumMediaType.Document)
            {
                return SupportedMediaTypes.DocumentTypes;
            }

            if (album.MediaType == AlbumMediaType.Photo)
            {
                return SupportedMediaTypes.PhotoTypes;
            }

            if (album.MediaType == AlbumMediaType.Video)
            {
                return SupportedMediaTypes.VideoTypes;
            }
            if (album.MediaType == AlbumMediaType.Mix)
            {
                return SupportedMediaTypes.AudioTypes + SupportedMediaTypes.DocumentTypes + SupportedMediaTypes.PhotoTypes + SupportedMediaTypes.VideoTypes;
            }

            return "*.doc";
        }

        private string GetExtensionsForUploadFile(Guid id)
        {
            var repo = Repository;
            var album = AlbumCompiledQueries.GetAlbum(repo as Repository, id);
            if (album.MediaType == AlbumMediaType.Audio)
            {
                return "*.mp3; *.wma; *.wav;";
            }

            if (album.MediaType == AlbumMediaType.Document)
            {
                return "*.txt; *.doc; *.pdf; *.docx; *.xls;";
            }

            if (album.MediaType == AlbumMediaType.Photo)
            {
                return "*.jpg; *.jpeg; *.png; *.bmp; *.gif; *.tiff;";
            }

            if (album.MediaType == AlbumMediaType.Video)
            {
                return "*.avi; *.mpg; *.mpeg; *.mov;";
            }
            if (album.MediaType == AlbumMediaType.Mix)
            {
                return "*.mp3; *.wma; *.wav;" + "*.txt; *.doc; *.pdf; *.docx; *.xls;" + "*.jpg; *.jpeg; *.png; *.bmp; *.gif; *.tiff;" + "*.avi; *.mpg; *.mpeg; *.mov;";
            }

            return "*.doc";
        }

        private string GetPath(Media file)
        {
            var repo = Repository;
            var album = AlbumCompiledQueries.GetAlbumByMediaId(repo as Repository, file.Id);
            var fileSubject = MediaCompiledQueries.GetMediaSubject(repo as Repository, file.Id);
            return Server.MapPath("~/Media/" + fileSubject.Id + "/" + album.Id + "/" + file.Id + "." + file.FileType);
        }

        #endregion
    }

}
